(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.dataInquiry.runListController', runListController);
	runListController.$inject = ['$rootScope', '$scope', '$q', 'Constants', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService',
			'dataInquiryService' ];
	function runListController($rootScope, $scope, $q, Constants, gridService, modalService, layoutConfig, validatorConfig, authService, dataInquiryService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("dataInquiryList");
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		
		ctrl.init = function() {
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, rowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.searchCriteria.list';
			ctrl.searchCriteria = ctrl.gridOptions.defaultSearchCriteria;
			ctrl.search();
		};

		ctrl.run = function() {
			if (!ctrl.selectedRows || ctrl.selectedRows.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.info.norecsel' ]
				});
				return;
			}
			$scope.go('cda.dataInquiry.run', ctrl.selectedRows[0]);
		};

		ctrl.search = function() {
			ctrl.searchCriteria.list = [];
			authService.search(ctrl.searchCriteria).then(
			function(response) {
				angular.merge(ctrl.searchCriteria, response.data);
				gridService.updateGridOptions(ctrl.searchCriteria, ctrl.gridOptions);
				ctrl.serviceCodeOptions = ctrl.searchCriteria.services;
			},angular.noop);
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.searchCriteria.pageNum = pageNum;
			ctrl.searchCriteria.pageSize = pageSize;
			ctrl.searchCriteria.list = [];
			ctrl.search();
		}

		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
			$rootScope.initAuditOrNoteParams("","");
		}

		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.searchCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.searchCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
	}
})(angular);